<?php


namespace App\Utils;

use Exception;

class Encrypt
{
    protected $key;
    protected $data;
    protected $method;
    protected $iv;
    protected $blockSize;
    protected $mode;

    /**
     * Available OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING
     *
     * @var int $options
     */
    protected $options = 0;

    /**
     *
     * @param string $data
     * @param string $key
     * @param int $blockSize
     * @param string $mode
     */
    function __construct($data) {
        $this->data = $data;
        $this->key = '0cc05b71fcc2b5f9';
        $this->blockSize = 128;
        $this->mode = 'ECB';
        $this->iv = '';
        $this->setMethod($this->blockSize, $this->mode);
    }


    /**
     * 设置加密模式，如 AES-128-CBC
     * @param int $blockSize
     * @param string $mode
     */
    public function setMethod($blockSize, $mode = 'CBC') {
        if($blockSize==192 && in_array('', array('CBC-HMAC-SHA1','CBC-HMAC-SHA256','XTS'))) {
            $this->method=null;
            throw new Exception('Invlid block size and mode combination!');
        }
        $this->method = 'AES-' . $blockSize . '-' . $mode;
    }

    /**
     * 验证信息
     * @return boolean
     */
    public function validateParams() {
        if ($this->data != null &&
            $this->method != null ) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 加密
     * @return string
     */
    public function encrypt() {
        if ($this->validateParams()) {
            return trim(openssl_encrypt($this->data, $this->method, $this->key, $this->options,$this->iv));
        } else {
            throw new Exception('加密参数错误');
        }
    }

    /**
     * 解密
     * @return string
     * @throws Exception
     */
    public function decrypt() {
        if ($this->validateParams()) {
            $ret = openssl_decrypt($this->data, $this->method, $this->key, $this->options,$this->iv);
            return   trim($ret);
        } else {
            throw new Exception('密文参数错误');
        }
    }

}